<template>
  <v-card outlined>
    <v-card-subtitle>{{ label }}</v-card-subtitle>
    <v-card-text>
      <slot name="preview" v-bind="{ fileStore: localFileStore }"></slot>
    </v-card-text>
    <v-card-text>
      <v-file-input
        v-model="file"
        show-size
        counter
        :multiple="false"
        :accept="accept"
        clearable
        label="选择文件上传"
        small-chips
      ></v-file-input>
    </v-card-text>
    <v-card-actions>
      <v-btn color="primary" @click.stop="onDelete">删除</v-btn>
      <v-btn color="primary" @click.stop="onUpload">上传到服务器</v-btn>
    </v-card-actions>
  </v-card>
</template>

<script>
  // 上传图片的对话框组件
  import merge from "lodash/merge"
  import { FileStore } from "@/store/models/file"

  export default {
    name: "UploaderBase",
    model: {
      prop: "fileStore",
      event: "update:fileStore",
    },
    props: {
      fileStore: {
        type: Object,
        required: false,
        default: null
      },
      parent_dir: {
        type: String,
        required: false,
        default: undefined,
      },
      label: {
        type: String,
        required: false,
        default: "选择本地文件上传",
      },
      accept: {
        type: String,
        required: false,
        default: "",
      },
    },
    data: () => ({
      showDialog: false,
      localFileStore: new FileStore(),
      file: null,
    }),
    watch: {
      fileStore(val, oldVal) {
        if (val) {
          this.localFileStore = val
        }else{
          this.localFileStore = new FileStore()
        }
      },
    },
    mounted() {
      if (this.fileStore) {
        this.localFileStore = this.fileStore
      }else{
        this.localFileStore = new FileStore()
      }
    },
    methods: {
      onDelete(){
        this.file = null
        this.localFileStore = null
        this.$emit("update:fileStore", null)
      },
      async onUpload() {
        if (!this.file) {
          this.$dialog.notify.info("未选择文件")
          return
        }
        const file_store = await FileStore.upload(this.file, this.parent_dir)
        this.localFileStore = file_store
        this.$emit("update:fileStore", this.localFileStore)
      },
    },
  }
</script>
